package com.mango.iot.gateway.http.srv;

import com.alibaba.fastjson.JSONObject;
import com.mango.iot.gateway.http.controller.req.AuthReq;
import com.mango.iot.gateway.http.core.redis.RedisUtils;
import com.mango.iot.gateway.http.srv.dto.DeviceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Token 服务
 *
 * @author liangfeihu
 * @since 2021/8/24 17:43
 */
@Service
public class TokenService {

    private static final String HTTP_TOKEN_PREFIX = "GATEWAY_HTTP_WEB:HTTP:TOKEN:";

    @Autowired
    private RedisUtils redisUtils;

    public void setTokenToCache(String token, AuthReq authReq) {
        DeviceInfo deviceInfo = new DeviceInfo(authReq.getProductKey(), authReq.getDeviceNo(), authReq.getClientId());
        redisUtils.set(HTTP_TOKEN_PREFIX + token, JSONObject.toJSONString(deviceInfo), 7 * 24 * 3600);
    }

    public void delTokenInCache(String token) {
        redisUtils.delete(HTTP_TOKEN_PREFIX + token);
    }

    public DeviceInfo getDeviceInfoInCache(String token) {
        Object cacheObj = redisUtils.get(HTTP_TOKEN_PREFIX + token);
        DeviceInfo deviceInfo = null;
        if (cacheObj != null) {
            deviceInfo = JSONObject.parseObject(cacheObj.toString(), DeviceInfo.class);
        }
        return deviceInfo;
    }

}
